<!-- 消息组别编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="460"
    :model-value="modelValue"
    :title="isUpdate ? '编辑消息组别' : '新增消息组别'"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="组别名称" prop="name">
        <el-input v-model="form.name" clearable :maxlength="20" placeholder="请输入消息组别名称" />
      </el-form-item>
      <el-form-item label="消息模版" prop="nt_ids">
        <el-select v-model="form.nt_ids" clearable filterable multiple>
          <el-option v-for="item in props.templateList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="组别状态" prop="status">
        <el-radio-group v-model="form.status" placeholder="请选择状态">
          <el-radio label="正常" :value="1" />
          <el-radio label="禁用" :value="2" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save"
      >
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
  templateList: Array,
})

const emit = defineEmits(['done', 'update:modelValue'])

/** 是否是修改 */
const isUpdate = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  id: undefined,
  name: '',
  nt_ids: [],
  status: 1,
})

/** 表单验证规则 */
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入消息组别名称',
      type: 'string',
      trigger: 'blur',
    },
  ],
  nt_ids: [
    {
      required: true,
      message: '请选择消息模板',
      type: 'array',
      trigger: 'blur',
    },
  ],
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true
    utils.post('/noticeGroup/edit', form)
      .then((res) => {
        utils.message(res.msg, res.success)
        updateModelValue(false)
        emit('done')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      if (props.data) {
        assignFields(props.data)
        isUpdate.value = true
      }
      else {
        isUpdate.value = false
      }
    }
    else {
      resetFields()
      formRef.value?.clearValidate?.()
    }
  },
)
</script>
